#pragma once

#include <iostream>
#include <cstring>
#include <cerrno>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"

namespace Alpaca
{
    const uint16_t defaultport = 8080;
    using func_t = std::function<std::string(std::string)>;
    class UdpServer
    {
    public:
        UdpServer(func_t service, int port = defaultport)
            : _port(port), _service(service)
        {
        }
        ~UdpServer()
        {
        }
        void InitServer()
        {
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cout << "create socket error: " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }

            std::cout << "create socket success: " << _sock << std::endl;

            struct sockaddr_in local;
            bzero(&local, sizeof local);
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;

            if (bind(_sock, (sockaddr *)&local, sizeof(local)))
            {
                std::cout << "bind socket error: " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success" << std::endl;
        }
        void Start()
        {
            char buffer[1024];
            while (true)
            {
                // 接收信息
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
                if (n > 0)
                    buffer[n] = '\0';
                else
                    continue;

                // 提取客户端信息
                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t port = ntohs(peer.sin_port);
                std::cout << "get message from " << clientip << "-" << port << ": " << buffer << std::endl;

                std::string resp = _service(buffer);

                // 发送信息
                sendto(_sock, resp.c_str(), resp.size(), 0, (sockaddr *)&peer, sizeof(peer));
            }
        }

    private:
        int _sock;
        uint16_t _port;
        func_t _service;
    };
}